<?php
/**
 * @author Raven <karascanvas@qq.com>
 */
namespace library\tencent\wechat\wechat_index;

use library\tencent\wechat\admin_wechat\Settings;
use library\tencent\wechat\admin_wechat\WechatMpService;
use library\tencent\wechat\common\WechatMP;
use think\Cookie;
use think\Db;

abstract class SdkConfig
{
    private function __construct() { }
    // <editor-fold defaultstate="collapsed" desc="获取随机数">
public static function make_nonceStr(){
        $codes='';
        $codeSet = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0; $i<16; $i++) {
            $codes[$i] = $codeSet[mt_rand(0, strlen($codeSet)-1)];
        }
        $nonceStr = implode($codes);
        return $nonceStr;
    }
// </editor-fold>


// <editor-fold defaultstate="collapsed" desc="返回配置参数">
public static function make_signature()
    {
        $nonceStr = static::make_nonceStr();//随机码
        $timestamp = time();
        $cfg=Settings::get('wechat_mp_config');

        if(Cookie::get('wechat_jsapi_ticket')){
            $jsapi_ticket=Cookie::get('wechat_jsapi_ticket');
        }else{
            $access_token=WechatMpService::getAccessToken();
            $ticket=WechatMP::make_ticket($access_token);
            $jsapi_ticket=$ticket->getData()['ticket'];
            Cookie::set('wechat_jsapi_ticket',$jsapi_ticket,7000);
        }
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string1 = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string1);//获得签名
        $arr = array(
            'appid' => $cfg['app_id'],
            'signature' => $signature,
            'time' => $timestamp,
            'nonceStr' => $nonceStr,
            'jsapi_ticket' => $jsapi_ticket,
            'url' =>$url,
            'string1' => $string1
        );
        return $arr;
    }

    public static function jssdk(){
        return static::make_signature();
    }
// </editor-fold>
}